pageGen = {
	setCookie: function (c_name, value, exdays){
		var exdate=new Date();
		exdate.setDate(exdate.getDate() + exdays);
		var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
		document.cookie=c_name + "=" + c_value;
	},
	
	getCookie: function(c_name){
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++)
		{
		  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		  x=x.replace(/^\s+|\s+$/g,"");
		  if (x==c_name)
			{
			return unescape(y);
			}
		}
	},
	
	checkCookie: function()
	{
	var price=this.getCookie("price");
	  if (price!=null && price!="")
	  {
		//loadPageInProgress
		progressGen.generateBox();
	  }
		else 
		{
		boxGen.generateBox();
		}
	},
	
	deleteCookie: function(c_name) {
    document.cookie = encodeURIComponent(c_name) + "=deleted; expires=" + new Date(0).toUTCString();
	}

};

getURL = {
	saveURL: function(){
			var tablink;
		  chrome.tabs.query({active : true, currentWindow: true}, function(tabs) {
		  		tablink=tabs[0].url;	
					pageGen.setCookie("url", tablink.toString(), 50);
		  });
			
	}
}
boxGen = {
	
	generateBox: function(){
		getURL.saveURL();
		var i = 0;
		var price = 25;
		

	var img = document.createElement('img');
		img.src = "/paypal.png";
		img.id = "logo";
		
	var img1 = document.createElement('img');
		img1.src="/box.png";
		img1.id = "article";
		
	var email=document.createElement('input');
		email.setAttribute("type","text");
		email.setAttribute("name","email");
		email.setAttribute("placeholder","E-mail");	
		email.setAttribute("id","email0");	
		
	var button=document.createElement('input');
		button.setAttribute("type","submit");
		button.setAttribute("value","Split it with friends");	
	var addbutton=document.createElement('img');
		addbutton.setAttribute("src","/plus.png");
		addbutton.setAttribute("height","32px");
		addbutton.setAttribute("width","32px");
		addbutton.setAttribute("id","addbutton");
	var minusbutton=document.createElement('img');
		minusbutton.setAttribute("src","/minus.png");
		minusbutton.setAttribute("height","32px");
		minusbutton.setAttribute("width","32px");	
	var more=document.createElement('span');
		more.setAttribute("id","more");	
	var div=document.createElement('div');
	div.setAttribute("id","buttondiv");	
	div.appendChild(addbutton);
	div.appendChild(minusbutton);

		document.body.appendChild(img);
		document.body.appendChild(img1);
		document.body.appendChild(email);
		document.body.appendChild(more);
		document.body.appendChild(div);
		document.body.appendChild(button);		


		



		button.onclick=function(){
			var invoiceIDArray = new Array();
			var emailArray = new Array();
			for(var j = 0; j <= i; j++){
				
				emailArray[j] = document.getElementById("email"+j).value;
				var e = emailArray[j];
				invoiceIDArray[j] = invoiceGenerator.generateInvoice(e);
			}
			stringEmail = emailArray.toString();
			stringIDs = invoiceIDArray.toString();
			pageGen.setCookie("emails", stringEmail, 50);
			pageGen.setCookie("invoiceIDs", stringIDs, 50);
			pageGen.setCookie("price", price.toString(), 50);
			//refresh?
			//window.opener.location.reload();
			clearWindow.clear(i);
			progressGen.generateBox();
		};
		
		
		
		

		// button.onclick=function(){//invoiceGenerator.generateInvoice(form.value);
			// progressGen.generateBox();
			// };
		var i=0;

		addbutton.onclick=function() {
			  i++;
		    var element = document.createElement("input");
		    element.setAttribute("type", "text");
		    element.setAttribute("name", "email");
		    element.setAttribute("id", "email"+i);
		    element.setAttribute("placeholder", "E-mail"); 
		    document.getElementById("more").appendChild(element);
		};
		minusbutton.onclick=function() {
			  if (i > 0){
					var element=document.getElementById("email"+i);
					element.parentNode.removeChild(element);
					i--;
			  }
		};
	
	
	}
	

};

clearWindow = {
	clear: function(i){
			var el = document.body;
			while(el.hasChildNodes()){
				el.removeChild(el.lastChild);
			}
			// while(i>0){
				// var element = document.getElementById("email"+i);
				// element.parentNode.removeChild(element);
				// i--;
			// }
	}
}
	

invoiceGenerator = {	
	generateInvoice: function(e){
	//e = 'buyer_1361659114_per@gmail.com';
	//alert(e);
	var params = 'requestEnvelope.errorLanguage=en_US'+
	'&invoice.merchantEmail=seller_1361655862_biz%40gmail.com'+ 
	'&invoice.payerEmail='+encodeURIComponent(e)+
	'&invoice.currencyCode=USD'+
	'&invoice.itemList.item(0).name=testShare'+
	'&invoice.itemList.item(0).description=testsCase'+
	'&invoice.itemList.item(0).quantity=1'+
	'&invoice.itemList.item(0).unitPrice=100'+
	'&invoice.itemList.item(0).taxName=Tax1'+
	'&invoice.itemList.item(0).taxRate=3'+
	'&invoice.paymentTerms=Net10';
	var invoiceGen_ =  'https://svcs.sandbox.paypal.com/Invoice/CreateAndSendInvoice?';
	
	var invoiceGen_2 = invoiceGen_ + params;
	//prompt(invoiceGen_2);
	req = new XMLHttpRequest();
	req.onreadystatechange=function(){
		if(req.readyState==4 && req.status==200){
			//var data=JSON.parse(req.responseText);
			//console.log(data.invoiceID);
			//alert(e);
			//return data.invoiceID;
		}
		else{
			console.log("THISASASDASDAS");
		}
	}
	req.open("GET", invoiceGen_2, true);
	
	req.setRequestHeader("X-PAYPAL-SECURITY-USERID","seller_1361655862_biz_api1.gmail.com");
	req.setRequestHeader("X-PAYPAL-SECURITY-PASSWORD","1361655887");
	req.setRequestHeader("X-PAYPAL-SECURITY-SIGNATURE","AZcLWYX0sb8NyfXkSP7RTto-K8-5A8m0nbbLA7ORR9yZWclj9o2fSpQL");
	req.setRequestHeader("X-PAYPAL-REQUEST-DATA-FORMAT", "NV");
	req.setRequestHeader("X-PAYPAL-RESPONSE-DATA-FORMAT", "JSON");
	req.setRequestHeader("X-PAYPAL-APPLICATION-ID", "APP-80W284485P519543T");

	req.send();
	},
	searchFromHistory: function(){
		var transactionSearch_ = 'https://api-3t.sandbox.paypal.com/nvp?'+
		'&USER=seller_1361655862_biz_api1.gmail.com'+
		'&PWD=1361655887'+
		'&SIGNATURE=AZcLWYX0sb8NyfXkSP7RTto-K8-5A8m0nbbLA7ORR9yZWclj9o2fSpQL'+
		'&VERSION=71.0'+
		'&METHOD=TransactionSearch'+
		'&STARTDATE=2013-02-24T00:00:00Z';	
		req = new XMLHttpRequest();
		var boolArr=new Array();
		req.onreadystatechange=function(){
			if(req.readyState==4 && req.status==200){
			var data=req.responseText;
			var emailArr=pageGen.getCookie("emails").split(",");
			for(var i=0;i<emailArr.length;i++){
				if(data.search(encodeURIComponent(emailArr[i]))!=-1){
					boolArr[i]=1;
				}
				else{
					boolArr[i]=0;
				}
			}
			}
		}
		
		req.open("GET", transactionSearch_, false);
		req.send();
		return boolArr;
	}
	
	
};


	

// Run our kitten generation script as soon as the document's DOM is ready.
document.addEventListener('DOMContentLoaded', function () {
	pageGen.checkCookie();
	getURL.saveURL();
  //boxGen.generateBox();
  //invoiceGenerator.generateInvoice();
	
});

clearWindow = {
	clear: function(){
		var e1 = document.body;
		while(e1.hasChildNodes()){
			e1.removeChild(e1.lastChild);
		}
	}
	
}

progressGen = {
	generateBox: function(){
	//var flag;
	var img1 = document.createElement('img');
		img1.src="/box.png";
		img1.id = "article";
		
		var refresh = document.createElement('img');
				refresh.src="/refresh.png";
				refresh.id = "refresh";	
				
				refresh.onclick=function(){
				 	flag = true;
					clearWindow.clear();
					pageGen.checkCookie();
				}
				
	var reset = document.createElement('img');
			reset.src="/reset.png";
			reset.id = "reset";

			reset.onclick=function(){
				pageGen.deleteCookie("emails");
				pageGen.deleteCookie("price");
				pageGen.deleteCookie("invoiceIDs");
				clearWindow.clear();
				boxGen.generateBox();
				flag=false;
			}
		
	var pricediv=document.createElement('div');
		pricediv.setAttribute("class","centerdiv");		
	var price = document.createTextNode(pageGen.getCookie("price")+" $");
	pricediv.appendChild(price);
				
	

	var container=document.createElement('div');
	container.setAttribute("id","container");
	var progressbar=document.createElement('div');
	progressbar.setAttribute("id","progressbar");
	container.appendChild(progressbar);
	

	var pgbardiv=document.createElement('div');
	pgbardiv.setAttribute("class","centerdiv");

	
	document.body.appendChild(img1);
	document.body.appendChild(container);
	document.body.appendChild(pgbardiv);

	var emailContainer=document.createElement('div');
	var emai=pageGen.getCookie("emails");
	
	var emailArr = emai.split(",");
	console.log(emailArr);
	var invoiceIDs = pageGen.getCookie("invoiceIDs").split(',');
	
	var boolArr = new Array();
	for(var j = 0; j < emailArr.length; j++){
		boolArr[j] = invoiceGenerator.searchFromHistory(invoiceIDs[j], emailArr[j]);
	}
	
	
		console.log(boolArr);

	document.body.appendChild(reset);
	document.body.appendChild(img1);
	document.body.appendChild(container);
	document.body.appendChild(pgbardiv);
	
	document.body.appendChild(refresh);
	document.body.appendChild(reset);
	document.body.appendChild(img1);
	document.body.appendChild(pricediv);
	document.body.appendChild(container);

	var vide=document.createElement('div');
	document.body.appendChild(vide);
	
	var j=0;
		
		
	
	for(var i=0;i<emailArr.length;i++){

		if((flag == true)&&i==0){

			var emailContainer=document.createElement('div');
			emailContainer.setAttribute("id","emailyes");

			emailContainer.appendChild(document.createTextNode(emailArr[i]));


			document.body.appendChild(emailContainer);
			j++;

		}
		
		
		else {

			var emailContainer=document.createElement('div');
			emailContainer.setAttribute("id","emailno");

			emailContainer.appendChild(document.createTextNode(emailArr[i]));

			document.body.appendChild(emailContainer);
		}	
	}
	


	
	

	document.getElementById("progressbar").style.width=j/emailArr.length*100+"%";
	var percentage=document.createTextNode(" "+j+" / "+emailArr.length);
	pgbardiv.appendChild(percentage);	
	document.body.insertBefore(pgbardiv, vide);
	
	if (j==emailArr.length){
		var button=document.createElement('input');
				button.setAttribute("type","submit");
				button.setAttribute("value","Proceed to Purchase");
		document.body.appendChild(button);
		button.onclick=function(){
			console.log(pageGen.getCookie('url'));
			chrome.tabs.create({url:pageGen.getCookie('url')});
		}	
		}



	}




};
